package cc.zy.base.hr.controller;

import cc.zy.base.common.annotation.ControllerEndpoint;
import cc.zy.base.common.controller.BaseController;
import cc.zy.base.common.entity.FebsConstant;
import cc.zy.base.common.entity.FebsResponse;
import cc.zy.base.common.entity.QueryRequest;
import cc.zy.base.common.exception.FebsException;
import cc.zy.base.common.utils.DateUtil;
import cc.zy.base.common.utils.FebsUtil;
import cc.zy.base.hr.entity.Course;
import cc.zy.base.hr.service.ICourseService;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.wuwenze.poi.ExcelKit;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 员工标签
 * Controller
 * 
 * */
@Slf4j
@Validated
@Controller("hrView_course")
@RequiredArgsConstructor
public class CourseController extends BaseController {

    private static final Integer MAXID = 63000;
    private static final Integer MINID = 60000;

    @Resource
    private final ICourseService courseService;

     /**
          * 
          *
          * @Author miaochun
          * @since  2022/3/7 下午 3:29
          * @param 
          * @return 
          */
    @GetMapping(FebsConstant.VIEW_PREFIX + "course/goList")
    public String courseIndex() {
        return FebsUtil.hrView("course/course");
    }
    
     /**
          * 
          *
          * @Author miaochun
          * @since  2022/3/7 下午 3:30
          * @param 
          * @return 
          */
    @GetMapping("course/list")
    @ResponseBody
    public FebsResponse courseList(QueryRequest request, Course course) {
        
        log.debug("前台传来的对象是：" + course);
        
        Map<String, Object> dataTable = getDataTable(courseService.findCourses(request, course));
        
        return new FebsResponse().success().data(dataTable);
    }

         /**
          * 删除用户标签
          *
          * @Author miaochun
          * @Date 2022/3/7
          * @param 
          * @return FebsResponse
          */
    @GetMapping("course/delete/{courseIds}")
    @ControllerEndpoint(operation = "删除用户标签", exceptionMessage = "删除用户标签异常")
    @ResponseBody
    public FebsResponse deleteCourses(@NotBlank(message = "{required}") @PathVariable String courseIds) {
        
        String[] ids = courseIds.split(StringPool.COMMA);
        
        courseService.deleteCourses(ids);
        
        return new FebsResponse().success();
    }
     /**
          * 
          *
          * @Author miaochun
          * @since  2022/3/7 下午 3:31
          * @param 
          * @return 
          */
    @PostMapping("course/update")
    @ControllerEndpoint(operation = "修改用户标签", exceptionMessage = "修改用户标签信息异常")
    @ResponseBody
    public FebsResponse updateCourse(@Valid Course course, String myfile, String courseKeywords) {
        
        System.out.println("course = " + course);
        
        if (course.getId() == null) {
            throw new FebsException("用户ID为空");
        }

       
        String regEx= ",";
        String reStr= "，";
        Pattern pattern   =   Pattern.compile(regEx);
        Matcher matcher   =   pattern.matcher(courseKeywords);
        reStr = matcher.replaceAll(reStr).trim();
        System.out.println( reStr );

        course.setCourseKeywords(reStr);
        course.setLastModifyUserId(FebsUtil.getCurrentUser().getUserId());
        course.setAttachmentUrl(myfile);
        course.setLastModifyDate(new Date());
        
        courseService.updateCourse(course);
        
        return new FebsResponse().success();
    }

    
    @GetMapping("course/excel")
    @ControllerEndpoint(exceptionMessage = "导出Excel异常")
    public void export(HttpServletResponse response, Course course) {

        log.debug(String.format("response = %s", response));
        log.debug(String.format("course = %s", course));

        List<Course> courses = courseService.findCollageListNotPage(course);
        
        ExcelKit.$Export(Course.class, response).downXlsx(courses, false);
    }

    /**
     * 方法描述：查找用户简称
     *
     * @param courseId 用户id
     * @return cc.zy.base.common.entity.FebsResponse
     * @author houweikang
     * @date 2021/2/3
     */
    @GetMapping("course/findById/{courseId}")
    @ResponseBody
    public FebsResponse findById(@PathVariable Integer courseId) {

        log.debug(String.format("courseId = %s", courseId));

        Course course = courseService.findById(courseId);
        
        return new FebsResponse().success().data(course);
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "course/detail/{id}")
    public String courseDetail(@PathVariable Integer id, Model model) {
        
        resolveCourseModel(id, model, true);
        
        return FebsUtil.hrView("course/courseDetail");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "course/update/{id}")
    public String courseUpdate(@PathVariable Integer id, Model model) {
        
        resolveCourseModel(id, model, false);
        
        return FebsUtil.hrView("course/courseUpdate");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "course/add")
    public String courseAdd() {
        return FebsUtil.hrView("course/courseAdd");
    }

    

    @PostMapping("course/add")
    @ResponseBody
    @ControllerEndpoint(operation = "新增用户标签", exceptionMessage = "新增用户标签异常")
    public FebsResponse addCourse(@Valid Course course, String myfile ,String courseKeywords) {

        String regEx= ",";
        String reStr= "，";
        Pattern pattern   =   Pattern.compile(regEx);
        Matcher matcher   =   pattern.matcher(courseKeywords);
        reStr = matcher.replaceAll(reStr).trim();
        System.out.println( reStr );

        course.setCourseKeywords(reStr);
        course.setCreateUserId(FebsUtil.getCurrentUser().getUserId());
        course.setLastModifyUserId(FebsUtil.getCurrentUser().getUserId());
        course.setAttachmentUrl(myfile);
        
       
        
        courseService.createCourse(course);

        return new FebsResponse().success();
    }

    @GetMapping("course/isRepetitive")
    @ResponseBody
    public Boolean isRepetitive(String courseName) {
        
        System.out.println("courseName = " + courseName);
        
       return courseService.isRepetitive(courseName);
    }

    private void resolveCourseModel(Integer id, Model model, Boolean transform) {
        
        Course course = courseService.findById(id);
        
        if (course.getCreateDate() != null) {
            model.addAttribute("createDateTime", DateUtil.getDateFormat(course.getCreateDate(), DateUtil.FULL_TIME_SPLIT_PATTERN));
        }
        if (course.getLastModifyDate() != null) {
            model.addAttribute("updateDateTime", DateUtil.getDateFormat(course.getLastModifyDate(), DateUtil.FULL_TIME_SPLIT_PATTERN));
        }
        
        System.out.println("course = " + course);
        
        model.addAttribute("course", course);
    }
}